#include "rankwidget.h"
#include "userwidget.h"
#include "ui_rankwidget.h"
#include <QMessageBox>
#include <QJsonObject>
#include <QJsonDocument>
#include <QDebug>
#include <algorithm>

RankWidget::RankWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RankWidget),
    m_networkAccessManager(Q_NULLPTR)
{
    ui->setupUi(this);

    // 显示用户数据
    if (!m_networkAccessManager)
        m_networkAccessManager = new QNetworkAccessManager(this);
    connect(m_networkAccessManager, &QNetworkAccessManager::finished, this, [&](QNetworkReply *reply) {
        m_networkAccessManager->disconnect();
        m_users = QJsonDocument::fromJson(reply->readAll()).array();
        auto userList = m_users.toVariantList();
        std::sort(userList.begin(), userList.end(), [](const QVariant& a, const QVariant& b) {
            return a.toJsonObject().value("score").toInt() > b.toJsonObject().value("score").toInt();
        });


        for (qsizetype i = 0; i < m_users.size(); i++)
        {
            QFont font;
            font.setPointSize(14);

            // 插入排名label
            QLabel *rankLabel = new QLabel(QString::number(i + 1));
            rankLabel->setFont(font);
            layout()->addWidget(rankLabel);

            // 插入头像
            QLabel *portraitLabel = new QLabel();
            portraitLabel->setFont(font);
            portraitLabel->setMinimumSize(QSize(40, 40));
            portraitLabel->setMaximumSize(QSize(40, 40));
            portraitLabel->setScaledContents(true);
            portraitLabel->setPixmap(QPixmap(":/img/icon/apexbrainicon.png"));
            layout()->addWidget(portraitLabel);

            // 插入用户名
            QLabel *userIdLabel = new QLabel();
            userIdLabel->setFont(font);
            userIdLabel->setText(userList[i].toJsonObject().value("userId").toString());
            layout()->addWidget(userIdLabel);

            // 插入分数
            QLabel *scoreLabel = new QLabel();
            scoreLabel->setFont(font);
            scoreLabel->setText(QString::number(userList[i].toJsonObject().value("score").toInt()));
            layout()->addWidget(scoreLabel);
        }
        layout()->addItem(new QSpacerItem(40, 20, QSizePolicy::Minimum, QSizePolicy::Expanding));
    });
    QNetworkRequest request;
    request.setUrl(QUrl(Global::serverIp + QString("/user/get_user_first_ten")));
    m_networkAccessManager->get(request);
}

RankWidget::~RankWidget()
{
    delete ui;
}

void RankWidget::closeEvent(QCloseEvent *event)
{
    Global::userWidget->show();
}
